/**
 * 删除权限
 * @url admin/system/permission/sys/delete
 * @description 删除权限
 */
module.exports = {
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '删除成功' };
		
		// 业务逻辑开始-----------------------------------------------------------
		let { _id, ids } = data;
		
		if (!_id && !ids) {
			return { code: -1, msg: '请指定要删除的权限' };
		}
		
		let deleteIds = ids || [_id];
		
		// 检查是否有角色使用该权限
		let roleRes = await db.collection('uni-id-roles').get();
		let usedPermissions = [];
		roleRes.data.forEach(role => {
			if (Array.isArray(role.permission)) {
				role.permission.forEach(p => {
					let permId = typeof p === 'string' ? p : p.permission_id;
					if (deleteIds.includes(permId)) {
						usedPermissions.push(role.role_name);
					}
				});
			}
		});
		
		if (usedPermissions.length > 0) {
			return { code: -1, msg: `该权限正在被角色使用：${usedPermissions.join('、')}` };
		}
		
		// 删除权限
		await db.collection('uni-id-permissions')
			.where({ _id: _.in(deleteIds) })
			.remove();
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

